<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item :label="$t('monitor.jobName')" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          :placeholder="$t('monitor.jobNameInput')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('monitor.jobType')" prop="jobType">
        <el-select v-model="queryParams.jobType" :placeholder="$t('monitor.jobTypeSelect')" clearable size="small">
          <el-option
            v-for="dict in jobTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('monitor.status')" prop="status">
        <el-select v-model="queryParams.jobStatus" :placeholder="$t('monitor.statusSelect')" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('elButton.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('elButton.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['job_add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t('elButton.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['job_edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
        >{{ $t('elButton.change') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['job_start']"
          type="primary"
          icon="el-icon-video-play"
          size="mini"
          @click="handleStarts"
        >{{ $t('monitor.startAll') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['job_stop']"
          type="warning"
          icon="el-icon-video-pause"
          size="mini"
          @click="handleStops"
        >{{ $t('monitor.stopAll') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['job_refresh']"
          type="danger"
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshs"
        >{{ $t('monitor.resetAll') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['jobLog_view']"
          type="info"
          icon="el-icon-s-operation"
          size="mini"
          @click="handleJobLog"
        >{{ $t('monitor.logView') }}
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('monitor.number')" align="center" prop="id" width="80" />
      <el-table-column :label="$t('monitor.jobName')" align="center" prop="jobName" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.jobGroup')" align="center" prop="jobGroup" />
      <el-table-column :label="$t('monitor.jobType')" align="center" prop="jobType" :formatter="jobTypeFormat" />
      <el-table-column :label="$t('monitor.executePath')" align="center" prop="executePath" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.paramsValue')" align="center" prop="paramsValue" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.cronExpression')" align="center" prop="cronExpression" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.previousTime')" align="center" prop="previousTime" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.nextTime')" align="center" prop="nextTime" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('monitor.status')" align="center" prop="jobStatus" :formatter="statusFormat" />
      <el-table-column :label="$t('equipment.control')" align="center" class-name="small-padding fixed-width" width="260" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-hasPerm="['job_start']"
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="handleRun(scope.row)"
          >{{ $t('monitor.startOnce') }}
          </el-button>
          <el-button
            v-if="scope.row.jobStatus != 2"
            v-hasPerm="['job_start']"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleStart(scope.row)"
          >{{ $t('monitor.start') }}
          </el-button>
          <el-button
            v-if="scope.row.jobStatus == 2"
            v-hasPerm="['job_stop']"
            size="mini"
            type="text"
            icon="el-icon-video-pause"
            @click="handleStop(scope.row)"
          >{{ $t('monitor.stop') }}
          </el-button>
          <el-button
            v-hasPerm="['job_view']"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >{{ $t('monitor.detail') }}
          </el-button>
          <el-button
            v-hasPerm="['user_del']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
          >{{ $t('elButton.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" :modal-append-to-body="true" :append-to-body="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.jobName')" prop="jobName">
              <el-input v-model="form.jobName" :placeholder="$t('monitor.jobNameInput')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.jobGroup')" prop="jobGroup">
              <el-input v-model="form.jobGroup" :placeholder="$t('monitor.jobGroupInput')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.jobType')" prop="jobType">
              <el-select v-model="form.jobType" :placeholder="$t('role.choose')">
                <el-option
                  v-for="dict in jobTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.misfirePolicy')" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy" size="small">
                <el-radio-button label="1">{{ $t('monitor.misfirePolicy1') }}</el-radio-button>
                <el-radio-button label="2">{{ $t('monitor.misfirePolicy2') }}</el-radio-button>
                <el-radio-button label="3">{{ $t('monitor.misfirePolicy3') }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="executePath" label-width="180px">
              <span slot="label">
                {{ $t('monitor.executePathInfo') }}
                <el-tooltip placement="top">
                  <div slot="content">
                    {{ $t('monitor.executePathInfo1') }}
                    <br>{{ $t('monitor.executePathInfo2') }}
                    <br>{{ $t('monitor.executePathInfo3') }}
                    <br>{{ $t('monitor.executePathInfo4') }}
                    <br>{{ $t('monitor.executePathInfo5') }}
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-input v-model="form.executePath" :placeholder="$t('monitor.executePathInput')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.paramsValue')" prop="paramsValue">
              <el-input v-model="form.paramsValue" :placeholder="$t('monitor.paramsValueInput')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.cronExpression')" prop="cronExpression">
              <el-input v-model="form.cronExpression" :placeholder="$t('monitor.cronExpressionInput')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('equipment.remarks')" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" rows="3" :placeholder="$t('equipment.remarksInput')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('submitText') }}</el-button>
        <el-button @click="cancel">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>

    <!-- 任务日志详细 -->
    <el-dialog :title="$t('monitor.taskDetail')" :visible.sync="openView" width="720px" :modal-append-to-body="true" :append-to-body="true" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.number') + '：'">{{ form.id }}</el-form-item>
            <el-form-item :label="$t('monitor.jobName') + '：'">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.jobGroup') + '：'">{{ form.jobGroup }}</el-form-item>
            <el-form-item :label="$t('monitor.jobType') + '：'">{{ jobTypeFormat(form) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('monitor.executePath') + '：'" label-width="180px">{{ form.executePath }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.cronExpression') + '：'">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.nextTime') + '：'">{{ parseTime(form.nextTime) }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.workPolicy') + '：'">
              <div v-if="form.misfirePolicy == 0">{{ $t('monitor.workPolicy1') }}</div>
              <div v-else-if="form.misfirePolicy == 1">{{ $t('monitor.misfirePolicy1') }}</div>
              <div v-else-if="form.misfirePolicy == 2">{{ $t('monitor.misfirePolicy2') }}</div>
              <div v-else-if="form.misfirePolicy == 3">{{ $t('monitor.misfirePolicy3') }}</div>
            </el-form-item>
            <el-form-item :label="$t('equipment.createTime') + '：'">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('monitor.status') + '：'">{{ statusFormat(form) }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">{{ $t('closeText') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listJob,
  getJob,
  addJob,
  editJob,
  delJob,
  runJob,
  startJob,
  stopJob,
  startJobs,
  stopJobs,
  refreshJobs
} from '@/api/monitor/job'

export default {
  name: 'Job',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,
      // 任务组名字典
      jobTypeOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        jobName: undefined,
        jobType: undefined,
        status: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: this.$t('monitor.jobNameEmpty'), trigger: 'blur' }
        ],
        jobType: [
          { required: true, message: this.$t('monitor.jobTypeEmpty'), trigger: 'blur' }
        ],
        jobGroup: [
          { required: true, message: this.$t('monitor.jobGroupEmpty'), trigger: 'blur' }
        ],
        executePath: [
          { required: true, message: this.$t('monitor.executePathInfoEmpty'), trigger: 'blur' }
        ],
        cronExpression: [
          { required: true, message: this.$t('monitor.cronExpressionEmpty'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('job_type').then(response => {
      this.jobTypeOptions = response.data
    })
    this.getDicts('job_status').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.loading = true
      listJob(this.queryParams).then(response => {
        this.jobList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 任务类型名字典翻译
    jobTypeFormat(row, column) {
      return this.selectDictLabel(this.jobTypeOptions, row.jobType)
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.jobStatus)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        jobName: undefined,
        jobType: undefined,
        invokeTarget: undefined,
        cronExpression: undefined,
        misfirePolicy: 1,
        concurrent: 1,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /* 运行一次 */
    handleRun(row) {
      this.$confirm(this.$t('monitor.isFunction') + row.jobName + this.$t('monitor.isFunctionAfter'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return runJob(row.jobName, row.jobGroup)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function(err) {
        console.log(err)
      })
    },
    /* 启动任务 */
    handleStart(row) {
      this.$confirm(this.$t('monitor.enterStart') + row.jobName + this.$t('monitor.isFunctionAfter'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return startJob(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function(err) {
        console.log(err)
      })
    },
    /* 暂停任务 */
    handleStop(row) {
      this.$confirm(this.$t('monitor.enterStop') + row.jobName + this.$t('monitor.isFunctionAfter'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return stopJob(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function() {
      })
    },
    /** 任务详细信息 */
    handleView(row) {
      getJob(row.id).then(response => {
        this.form = response.data
        this.openView = true
      })
    },
    /** 任务日志列表查询 */
    handleJobLog() {
      this.$router.push('/jobLog')
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = this.$t('monitor.addJob')
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset()
      const id = row.id || this.ids
      getJob(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = this.$t('monitor.changeJob')
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            editJob(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('loginLog.changeSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addJob(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('addSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id
      this.$confirm(this.$t('monitor.deleteJob') + ids + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delJob(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {
      })
    },
    handleStarts() {
      this.$confirm(this.$t('monitor.startJob'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return startJobs()
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function() {
      })
    },
    handleStops() {
      this.$confirm(this.$t('monitor.stopJob'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return stopJobs()
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function() {
      })
    },
    handleRefreshs() {
      this.$confirm(this.$t('monitor.resetJob'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return refreshJobs()
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('monitor.implementSuccess'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm(this.$t('monitor.exportJob'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        // return exportJob(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>
